package cn.onesearch.service;

import cn.one.common.DtoUtil;
import cn.one.dto.Dto;
import cn.one.pojo.User;
import cn.one.vo.UserQueryVo;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService{
    //索引库容器
    @Resource
    private SolrTemplate solrTemplate;
    @Resource
    private SolrServer solrServer;


    //Dto实际就是User的变形,UserQueryVo是关键词+过滤条件+排序+分页+默认域+高亮
    public Dto searchUserPage(UserQueryVo userQueryVo) throws Exception{
        SolrQuery solrQuery = new SolrQuery();
        //关键词,也可以用于多条件,*:*代表查询所有,
        //单条件可以用setQuery(查询语句)*:*代表查询所有,
        //多条件的语句,字段:输入的条件 AND 字段:输入的条件 ...
                    //字段:输入的条件 OR 字段:输入的条件 ...
        solrQuery.setQuery("*:*");
        //过滤条件set一个属于单条件,set多个属于多条件
        if(!"".equals(userQueryVo.getPassword()) && null != userQueryVo.getPower()){
            solrQuery.set("fq","password : *a*");
            solrQuery.set("fq","password : *d*");
        }

        //排序
        if(userQueryVo.getSort()==1){
            solrQuery.addSort("", SolrQuery.ORDER.asc);
        }else{
            solrQuery.addSort("", SolrQuery.ORDER.desc);
        }
        //分页
        solrQuery.setStart(0);
        solrQuery.setRows(5);
        //默认域(可以指定为copyfield的复合域)
        solrQuery.set("df","字段1");
        //只查指定的域
        solrQuery.set("fl","字段1,字段2");
        //指定高亮域
        solrQuery.addHighlightField("");
        //设置高亮的前序,后序
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        solrQuery.setHighlightSimplePost("</span>");
        //执行查询
        QueryResponse response = solrServer.query(solrQuery);
        //文档结果集
        SolrDocumentList documents = response.getResults();

        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //Map k id v map
            //map k 域名 v List
                //List list.get(0)
        //总条数
        long numFound = documents.getNumFound();

        List<User> userList = new ArrayList<>();
        for(SolrDocument doc : documents ){
            User user = new User();
            user.setPassword((String)doc.get("password"));
            //user.set入多个参数
            userList.add(user);
        }

        return DtoUtil.returnDataSuccess(userList);


    }

}
